package com.hundsun.yr.universal.p2p.datahandler;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.base.BaseAppManager;
import com.hundsun.yr.universal.library.base.BaseWebActivity;
import com.hundsun.yr.universal.library.data.HSSharedPreferences;
import com.hundsun.yr.universal.library.view.hsdialog.HSDialog;
import com.hundsun.yr.universal.library.widget.HSToast;
import com.hundsun.yr.universal.p2p.HsApplication;
import com.hundsun.yr.universal.p2p.bean.AdSlideBeen;
import com.hundsun.yr.universal.p2p.bean.LoanProductBeen;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.ApiConstants2;
import com.hundsun.yr.universal.p2p.config.Config;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.interactor.impl.StringRequestGetInteractorImpl;
import com.hundsun.yr.universal.p2p.interactor.impl.StringRequestInteractorImpl;
import com.hundsun.yr.universal.p2p.listener.BaseMultiLoadedListener;
import com.hundsun.yr.universal.p2p.ui.activity.GestureLockLoginActivity;
import com.hundsun.yr.universal.p2p.ui.activity.IWantLoanActivity;
import com.hundsun.yr.universal.p2p.ui.activity.LoginActivity;
import com.hundsun.yr.universal.p2p.ui.activity.ManagementActivity;
import com.hundsun.yr.universal.p2p.ui.activity.WebFDDActivity;
import com.hundsun.yr.universal.p2p.ui.activity.WebFDDProtocolActivity;
import com.hundsun.yr.universal.p2p.ui.fragment.LoanFragment;
import com.hundsun.yr.universal.p2p.utils.AndroidDes3Util;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool2;
import com.hundsun.yr.universal.p2p.utils.CommTool;
import com.hundsun.yr.universal.p2p.utils.GsonTool;
import com.hundsun.yr.universal.p2p.utils.Logs;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

/**
 * 我要借款
 *
 * @author tonglj
 */
public class LoanHandler extends BaseDataHandler implements HSDialog.HSDialogOnItemClickListener {
    private String FLAG = "";

    private final String FLAG_LOAN_PRODUCT = "LOAN_PRODUCT_LIST_LOGIN";
    /**
     * 查看授信
     */
    public static String VIEWCREDIT = "VIEWCREDIT";
    /**
     * 申请借款
     */
    public static String APPLYLOAN = "APPLYLOAN";

    /**
     * 用户信息
     */
    private HSSharedPreferences sharedPreferences = null;

    /**
     * 初始化信息
     */
    /**
     * 缴费授权金额
     * @param v
     */
    private HSDialog payFeeDialog;

    /**
     * 还款授权金额
     * @param v
     */
    private HSDialog repFeeDialog;
    private HSSharedPreferences mConfigSP = null;

    private LoanFragment mLoanFrangment;

    private HSDialog authDialog;

    public LoanHandler(Context mContext, LoanFragment frag) {
        super(mContext);
        this.mLoanFrangment = frag;
        sharedPreferences = new HSSharedPreferences(mContext, Config.SPPath.file_userLoginedInfo);
        mConfigSP = new HSSharedPreferences(mContext, Config.SPPath.file_configInfo);
    }

    public LoanHandler(Context mContext) {
        super(mContext);
        sharedPreferences = new HSSharedPreferences(mContext, Config.SPPath.file_userLoginedInfo);
        mConfigSP = new HSSharedPreferences(mContext, Config.SPPath.file_configInfo);
    }

    /**
     * 新的借款申请
     *
     * @param objs
     */
    protected void addBorrowApply(final Object... objs) {
        StringRequestInteractorImpl requestinteractor = new StringRequestInteractorImpl(new BaseMultiLoadedListener<String>() {
            @Override
            public void onSuccess(String task_name, int event_tag, String data) throws Exception {
                try {
                    AdSlideBeen adSlideBeen = (AdSlideBeen) GsonTool.getInstanceByJson(AdSlideBeen.class, data);
                    switch (adSlideBeen.code) {
                        case Constants.REQUESTCODE_000000:
                            //访问网络成功
                            try {
                                String decode = AndroidDes3Util.decode(adSlideBeen.data, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), (Date.parse(adSlideBeen.timestamp) + "").substring((Date.parse(adSlideBeen.timestamp) + "").length() - 8, (Date.parse(adSlideBeen.timestamp) + "").length()));
                                String[] split = decode.split("\\n");
                                if (!TextUtils.equals(objs[8].toString(),"0")){
                                    Bundle bundle = new Bundle();
                                    bundle.putString(BaseWebActivity.BUNDLE_KEY_URL, decode.substring(decode.indexOf("<")));
                                    bundle.putString(BaseWebActivity.BUNDLE_KEY_TITLE, mContext.getString(R.string.sign_protocol_title));
                                    bundle.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, BaseWebActivity.LoadType.DATA.getIntValue());
                                    readyGo(WebFDDProtocolActivity.class, bundle);
                                    BaseAppManager.getInstance().getActivity(IWantLoanActivity.class).finish();
                                } else {
                                    Bundle bundle = new Bundle();
                                    bundle.putString(BaseWebActivity.BUNDLE_KEY_URL, split[1]);
                                    bundle.putString(BaseWebActivity.BUNDLE_KEY_TITLE, mContext.getString(R.string.sign_fdd));
                                    bundle.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, BaseWebActivity.LoadType.HTTP.getIntValue());
                                    readyGo(WebFDDActivity.class, bundle);
                                    BaseAppManager.getInstance().getActivity(IWantLoanActivity.class).finish();
                                }

                            } catch (Exception e) {
                                new HSToast(mContext).showToast(mContext.getString(R.string.date_error));
                                e.printStackTrace();
                            }
                            break;

                        case Constants.REQUESTCODE_100600:
                            showToast(mContext.getString(R.string.login_overdue));
                            CommTool.goToLogin(mContext);
                            break;
                            //重新签约
                        case Constants.REQUESTCODE_000002:
                            payFeeDialog = new HSDialog(mContext.getString(R.string.tips), adSlideBeen.getMsg(), "暂不签约",
                                    "重新签约", mContext, LoanHandler.this).setCancelable(false);
                            payFeeDialog.show();
                payFeeDialog.show();
                            break;
                            //还款授权金额
                        case Constants.REQUESTCODE_000001:
                            repFeeDialog = new HSDialog(mContext.getString(R.string.tips), adSlideBeen.getMsg(), "暂不签约",
                                    "重新签约", mContext, LoanHandler.this).setCancelable(false);
                            repFeeDialog.show();
                repFeeDialog.show();
                            break;
                        case Constants.REQUESTCODE_100020:

                            break;
                        case Constants.REQUESTCODE_100010:

                            break;

                        case Constants.REQUESTCODE_700020:
                            break;
                        case Constants.REQUESTCODE_700021:
                            authDialog = new HSDialog(mContext.getString(R.string.tips), adSlideBeen.msg, mContext.getString(R.string.cancel),
                                    mContext.getString(R.string.sure), mContext, LoanHandler.this).setCancelable(false);
                            authDialog.show();
                            break;
                        default:
                            showToast(adSlideBeen.msg);
                            break;
                    }
                } catch (Exception e){
                    new HSToast(mContext).showToast(mContext.getString(R.string.date_error));
                    e.printStackTrace();
                }
                closeProgress();
            }

            @Override
            public void onException(String task_name, String msg) {
                new HSToast(mContext).getSingleLongToast(msg).show();
                closeProgress();
            }
        });

        String zwgt_data = BaseRequestTool2.getFormatedDateString();
        JSONObject map = new JSONObject();
        try {
            map.put("loanid", objs[0]);
            map.put("amount", objs[1]);
            map.put("term", objs[2]);
            map.put("rate", objs[3]);
            map.put("purpose", objs[4]);
            map.put("ratecutid", objs[5]);
            map.put("pay_method", objs[6]);
            map.put("service_fee_show", objs[9]);
            Logs.e("map" + map.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        JSONObject jsonParams = CommTool.getJSONParams(map, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);
        requestinteractor.getRequestData(TaskConstants.TASK_APPLY, mContext.getString(R.string.root_url_test) + mContext.getString(R.string.api_loan_test)
                + TaskConstants.TASK_APPLY, Constants.EVENT_DATA, jsonParams, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, mContext.getString(R.string.api_loan_test)
                + TaskConstants.TASK_APPLY, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data));
    }


    /**
     * 请求借款产品数据
     *
     * @param objs
     */
    protected void loanProductList(final Object... objs) {
        HashMap<String, String> params = ApiConstants2.index(objs[0].toString());
        final String zwgt_data = BaseRequestTool2.getFormatedDateString();
        StringRequestGetInteractorImpl requestinteractor = new StringRequestGetInteractorImpl(new BaseMultiLoadedListener<String>() {
            @Override
            public void onException(String task_name, String msg) {
                Logs.e("aa");
                mLoanFrangment.addDatas(new ArrayList<LoanProductBeen>());
                showToast(msg);
                closeProgress();
            }

            @Override
            public void onSuccess(String task_name, int event_tag, String data) throws JSONException {
                Logs.e("bb");
                AdSlideBeen adSlideBeen = (AdSlideBeen) GsonTool.getInstanceByJson(AdSlideBeen.class, data);
                switch (adSlideBeen.code) {
                    case Constants.REQUESTCODE_000000:
                        //访问网络成功
                        try {
                            String decode = AndroidDes3Util.decode(adSlideBeen.data, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), (Date.parse(adSlideBeen.timestamp) + "").substring((Date.parse(adSlideBeen.timestamp) + "").length() - 8, (Date.parse(adSlideBeen.timestamp) + "").length()));
                            String[] split = decode.split("\\n");
                            ArrayList<LoanProductBeen> loanProductBeens = GsonTool.jsonToArrayList(split[1], LoanProductBeen.class);
                            //通知LoadFragment装载数据
                            mLoanFrangment.addDatas(loanProductBeens);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    case Constants.REQUESTCODE_200500:
                        mLoanFrangment.addDatas(new ArrayList<LoanProductBeen>());
                        break;
                    case Constants.REQUESTCODE_100600:
                        closeProgress();
                        showToast(adSlideBeen.msg);
                        sharedPreferences.putBoolean(UserInfo.ISLOGIN, false);
                        mLoanFrangment.addDatas(new ArrayList<LoanProductBeen>());

                        HsApplication.goGesture = true;
                        HsApplication.isSrcreenOn = false;
                        if (BaseAppManager.getInstance().getActivity(GestureLockLoginActivity.class) != null){
                            BaseAppManager.getInstance().getActivity(GestureLockLoginActivity.class).finish();
                        }

                        if (BaseAppManager.getInstance().getActivity(LoginActivity.class) == null){
                            CommTool.goToLogin(mContext);
                        }

//                        EventBus.getDefault().post(new EventCenter(Constants.EVENT_DATA_LOGIN_EXPIRED));
                        break;
                    case Constants.REQUESTCODE_100020:
                        //Header值为空--不做任何提示
                        mLoanFrangment.addDatas(new ArrayList<LoanProductBeen>());
                        break;
                    case Constants.REQUESTCODE_100010:
                        mLoanFrangment.addDatas(new ArrayList<LoanProductBeen>());
                        break;
                    default:
                        mLoanFrangment.addDatas(new ArrayList<LoanProductBeen>());
                        showToast(adSlideBeen.msg);
                        break;
                }
                closeProgress();
            }
        });

        requestinteractor.getRequestData(TaskConstants.TASK_INDEX, mContext.getString(R.string.root_url_test) + mContext.getString(R.string.api_loan_test)
                + TaskConstants.TASK_INDEX, Constants.EVENT_DATA, params, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, mContext.getString(R.string.api_loan_test)
                + TaskConstants.TASK_INDEX, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data));
    }

    @Override
    public void onItemClick(Object o, int position) {
        if (o == authDialog) {
            if (position != -1) {
                readyGo(ManagementActivity.class);
            }
        }else if(o==payFeeDialog){
            if (position != -1) {
                readyGo(ManagementActivity.class);
            }
        }else if (o==repFeeDialog){
            if (position != -1) {
                readyGo(ManagementActivity.class);
            }
        }
    }
}
